<template>
  <div class="address-container">
    <div class="address-header">
      <h2 class="page-title">收货地址管理</h2>
      <el-button 
        type="primary" 
        @click="showAddModal"
        class="add-btn"
      >
        <el-icon><Plus /></el-icon>
        添加新地址
      </el-button>
    </div>
    
    <!-- 地址列表 -->
    <div class="address-list">
      <div 
        v-for="(address, index) in addresses" 
        :key="address.id"
        class="address-item"
        :class="{ 'default-address': address.isDefault }"
      >
        <div class="address-content">
          <div class="address-header">
            <div class="address-name">
              <span class="name">{{ address.realName }}</span>
              <span class="phone">{{ address.phone }}</span>
              <span v-if="address.isDefault" class="default-tag">默认</span>
            </div>
            <div class="address-actions">
              <el-button 
                type="text" 
                size="small"
                @click="showEditModal(index)"
              >
                编辑
              </el-button>
              <el-button 
                type="text" 
                size="small"
                text-color="#ff4d4f"
                @click="confirmDeleteAddress(index)"
              >
                删除
              </el-button>
              <el-button 
                v-if="!address.isDefault"
                type="text" 
                size="small"
                text-color="$primary-color"
                @click="setDefaultAddress(index)"
              >
                设为默认
              </el-button>
            </div>
          </div>
          <div class="address-detail">
            <span class="region">{{ address.region.join(' ') }}</span>
            <span class="street">{{ address.address }}</span>
            <span class="zipcode" v-if="address.zipCode">({{ address.zipCode }})</span>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="addresses.length === 0" class="empty-state">
        <el-empty 
          description="您还没有添加收货地址，点击添加按钮创建"
          image="/assets/empty-address.png"
        >
          <template #image>
            <div class="empty-image">
              <el-icon><Location /></el-icon>
            </div>
          </template>
        </el-empty>
      </div>
    </div>
    
    <!-- 添加/编辑地址弹窗 -->
    <el-dialog 
      v-model="dialogVisible"
      :title="isEdit ? '编辑收货地址' : '添加收货地址'"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form 
        ref="addressFormRef" 
        :model="addressForm" 
        :rules="addressRules"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="realName">
          <el-input 
            v-model="addressForm.realName" 
            placeholder="请输入收货人姓名"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input 
            v-model="addressForm.phone" 
            placeholder="请输入手机号码"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择省/市/区"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="详细地址" prop="address">
          <el-input 
            v-model="addressForm.address" 
            placeholder="请输入详细地址信息"
            type="textarea"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="邮政编码" prop="zipCode">
          <el-input 
            v-model="addressForm.zipCode" 
            placeholder="请输入邮政编码"
            maxlength="6"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认收货地址</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSaveAddress"
          :loading="saving"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../../store/modules/user'
import { Plus, Location } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()
const dialogVisible = ref(false)
const isEdit = ref(false)
const editingIndex = ref(-1)
const saving = ref(false)
const addressFormRef = ref(null)

// 地址列表数据（模拟数据）
const addresses = ref([
  {
    id: '1',
    realName: '张三',
    phone: '13800138001',
    region: ['北京市', '朝阳区', 'CBD'],
    address: '建国路88号',
    zipCode: '100022',
    isDefault: true
  },
  {
    id: '2',
    realName: '张三',
    phone: '13800138002',
    region: ['上海市', '浦东新区', '陆家嘴'],
    address: '世纪大道100号',
    zipCode: '200120',
    isDefault: false
  }
])

// 表单数据
const addressForm = reactive({
  realName: '',
  phone: '',
  region: [],
  address: '',
  zipCode: '',
  isDefault: false
})

// 表单验证规则
const addressRules = {
  realName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '收货人姓名长度在2-20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, message: '详细地址至少5个字符', trigger: 'blur' }
  ],
  zipCode: [
    { pattern: /^\d{6}$/, message: '邮政编码为6位数字', trigger: 'blur' }
  ]
}

// 地区选项（模拟数据）
const regionOptions = [
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '朝阳区',
        label: '朝阳区',
        children: [
          { value: 'CBD', label: 'CBD' },
          { value: '三元桥', label: '三元桥' }
        ]
      },
      {
        value: '海淀区',
        label: '海淀区',
        children: [
          { value: '中关村', label: '中关村' },
          { value: '五道口', label: '五道口' }
        ]
      }
    ]
  },
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '浦东新区',
        label: '浦东新区',
        children: [
          { value: '陆家嘴', label: '陆家嘴' },
          { value: '张江', label: '张江' }
        ]
      },
      {
        value: '徐汇区',
        label: '徐汇区',
        children: [
          { value: '徐家汇', label: '徐家汇' },
          { value: '华山', label: '华山' }
        ]
      }
    ]
  }
]

// 初始化加载地址列表
const loadAddresses = async () => {
  try {
    // 模拟加载地址列表
    // 实际项目中应调用 userAPI.getAddresses()
    // const response = await userAPI.getAddresses()
    // addresses.value = response.data
  } catch (error) {
    console.error('加载地址列表失败:', error)
  }
}

// 显示添加地址弹窗
const showAddModal = () => {
  // 重置表单
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑地址弹窗
const showEditModal = (index) => {
  const address = addresses.value[index]
  // 复制地址数据到表单
  Object.assign(addressForm, {
    realName: address.realName,
    phone: address.phone,
    region: address.region,
    address: address.address,
    zipCode: address.zipCode,
    isDefault: address.isDefault
  })
  isEdit.value = true
  editingIndex.value = index
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(addressForm, {
    realName: '',
    phone: '',
    region: [],
    address: '',
    zipCode: '',
    isDefault: false
  })
  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }
}

// 保存地址
const handleSaveAddress = async () => {
  // 表单验证
  try {
    await addressFormRef.value.validate()
  } catch (error) {
    return
  }
  
  saving.value = true
  try {
    const formData = {
      ...addressForm,
      id: isEdit.value ? addresses.value[editingIndex.value].id : 'new_' + Date.now()
    }
    
    if (formData.isDefault) {
      // 如果设置为默认地址，取消其他地址的默认状态
      addresses.value.forEach(item => {
        item.isDefault = false
      })
    }
    
    if (isEdit.value) {
      // 编辑地址
      addresses.value[editingIndex.value] = formData
      // 实际项目中应调用 userAPI.updateAddress(formData.id, formData)
    } else {
      // 添加新地址
      addresses.value.push(formData)
      // 实际项目中应调用 userAPI.addAddress(formData)
    }
    
    ElMessage.success(isEdit.value ? '地址更新成功' : '地址添加成功')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error(isEdit.value ? '地址更新失败' : '地址添加失败')
    console.error('保存地址失败:', error)
  } finally {
    saving.value = false
  }
}

// 设置默认地址
const setDefaultAddress = async (index) => {
  try {
    // 模拟设置默认地址
    // 实际项目中应调用 userAPI.setDefaultAddress(addresses.value[index].id)
    
    // 取消其他地址的默认状态
    addresses.value.forEach(item => {
      item.isDefault = false
    })
    // 设置当前地址为默认
    addresses.value[index].isDefault = true
    
    ElMessage.success('默认地址设置成功')
  } catch (error) {
    ElMessage.error('设置默认地址失败')
    console.error('设置默认地址失败:', error)
  }
}

// 确认删除地址
const confirmDeleteAddress = (index) => {
  ElMessageBox.confirm(
    '确定要删除该收货地址吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await deleteAddress(index)
  }).catch(() => {
    // 用户取消删除
  })
}

// 删除地址
const deleteAddress = async (index) => {
  try {
    // 模拟删除地址
    // 实际项目中应调用 userAPI.deleteAddress(addresses.value[index].id)
    
    addresses.value.splice(index, 1)
    ElMessage.success('地址删除成功')
  } catch (error) {
    ElMessage.error('地址删除失败')
    console.error('删除地址失败:', error)
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 组件挂载时加载地址列表
onMounted(() => {
  loadAddresses()
})
</script>

<style scoped>
.address-container {
  background-color: #fff;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid $border-color;
  margin-bottom: 20px;
}

.page-title {
  font-size: $font-size-lg;
  font-weight: 500;
  color: $text-color;
  margin: 0;
}

.add-btn {
  height: 36px;
}

/* 地址列表 */
.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  padding: 0 20px 20px;
}

.address-item {
  border: 1px solid $border-color;
  border-radius: $border-radius-base;
  padding: 20px;
  transition: all 0.3s;
  position: relative;
}

.address-item:hover {
  border-color: $primary-color;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address-item.default-address {
  border-color: $primary-color;
  background-color: #f0f7ff;
}

.address-item.default-address::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background-color: $primary-color;
}

.address-content {
  width: 100%;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 10px 0;
  border-bottom: none;
  margin-bottom: 10px;
}

.address-name {
  display: flex;
  align-items: center;
  gap: 15px;
}

.name {
  font-weight: 500;
  color: $text-color;
}

.phone {
  color: $text-color-secondary;
}

.default-tag {
  background-color: $primary-color;
  color: #fff;
  font-size: $font-size-xs;
  padding: 2px 6px;
  border-radius: $border-radius-base;
}

.address-actions {
  display: flex;
  gap: 10px;
}

.address-detail {
  color: $text-color-secondary;
  line-height: 1.6;
}

.region {
  display: block;
  margin-bottom: 5px;
}

.street {
  display: block;
}

.zipcode {
  color: $text-color-placeholder;
}

/* 空状态 */
.empty-state {
  grid-column: 1 / -1;
  padding: 60px 20px;
  text-align: center;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin: 0 auto 20px;
  background-color: #f5f7fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-image .el-icon {
  font-size: 60px;
  color: #c0c4cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
    padding: 0 10px 10px;
    gap: 15px;
  }
  
  .address-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px 0;
  }
  
  .add-btn {
    margin-top: 10px;
  }
  
  .address-item {
    padding: 15px;
  }
  
  .address-actions {
    flex-direction: column;
    gap: 5px;
  }
  
  .address-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .address-name {
    margin-bottom: 10px;
  }
}
</style>